package com.example.zheng.qq.activity;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.zheng.qq.R;
import com.example.zheng.qq.entity.UseName;
import com.example.zheng.qq.util.Util;
import com.example.zheng.qq.view.Circle1;
import java.io.File;
import java.io.FileNotFoundException;


/**
 * Created by zheng on 17-4-22.
 */
public class InforActivity extends Activity{
    private ImageView mHeadImage;
    private File mStorePhoto;
    public static Uri mUri;
    public UseName useName;
    public SQLiteDatabase mDb=Util.Db;
    public static int i=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.infor_layout);
        useName= (UseName) getIntent().getSerializableExtra("user");
        View view=LayoutInflater.from(this).inflate(R.layout.head_image,null);
        View fragment=findViewById(R.id.f1);
        mHeadImage=(ImageView)findViewById(R.id.headImage);

        /**
         * 初始化头像
         */
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;//图片宽高都为原来的四分之一，即图片为原来的八分之一
            Bitmap bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse(useName.getHeadPicture())),null,options);
            Log.d("ss","开始吧");
            Bitmap b=Circle1.createCircle(bitmap);
            mHeadImage.setImageBitmap(b);
        } catch (Exception e) {
            e.printStackTrace();
        }

        /**
         * 给fragment绑定点击事件，而不能直接在xml文件里绑定，因为fragment这个布局没有onclick这个属性
         * 点击fragment就开启相机实现拍摄的功能
         */
        fragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("ss",mHeadImage+"");
                mStorePhoto=new File(getExternalCacheDir(),"head.image"+useName.getName());
                if (mStorePhoto.exists()){
                    mStorePhoto.delete();
                }else{
                    try {
                        mStorePhoto.createNewFile();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if(Build.VERSION.SDK_INT>=24){
                    mUri= FileProvider.getUriForFile(InforActivity.this,"com.example.cameraabumtest.fileprovider",mStorePhoto);

                }else{
                    mUri=Uri.fromFile(mStorePhoto);
                    Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,mUri);
                    startActivityForResult(intent,2);

                }
                i++;
            }
        });



    }

    /**为了头像能够更新出来，统一在onStart（）里设置，因为活动被创建或者再次回到顶部都会调用这个方法
     *
     */
    /*@Override
    protected void onStart() {
        try {

            Bitmap bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse(useName.getHeadPicture())));
            Log.d("ss","开始吧");
            Bitmap b=Circle1.createCircle(bitmap);
            mHeadImage.setImageBitmap(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onStart();
    }*/

    /**
     * 1.从相册中获取到图片
     * 2.获取到拍摄的图片，并替换头像
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);

        switch (requestCode){
            case 1:
                if(resultCode==RESULT_OK){
                    if(Build.VERSION.SDK_INT>=19){
                        handleImageOnKikat(data);


                    }else{
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            case 2:

                if(resultCode==RESULT_OK){
                    try {
                        BitmapFactory.Options options=new BitmapFactory.Options();
                        options.inSampleSize=4;
                        Bitmap bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(mUri),null,options);
                        Bitmap b=Circle1.createCircle(bitmap);
                        mHeadImage.setImageBitmap(b);
                        Log.d("qq",mUri.toString());
                        mDb.execSQL("update user set picture=? where uname=?",new String[]{mUri.toString()+"",useName.getName()});
                        Util.imageUri=mUri;

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

        }
    }
    private void handleImageBeforeKitKat(Intent data) {
        Uri uri=data.getData();
        String imagePath=getImagePath(uri,null);
        displayImage(imagePath);
    }

    private void handleImageOnKikat(Intent data) {
        String inmagePath=null;
        Uri uri=data.getData();
        if(DocumentsContract.isDocumentUri(this,uri)){
            String docId= DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id=docId.split(":")[1];
                String selection=MediaStore.Images.Media._ID+"="+id;
                inmagePath=getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri connectUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                inmagePath=getImagePath(connectUri,null);
            }
        }else if("content".equalsIgnoreCase(uri.getScheme())){
            inmagePath=getImagePath(uri,null);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            inmagePath=uri.getPath();
        }
        displayImage(inmagePath);

    }
    private void displayImage(String inmagePath) {
        if(inmagePath!=null){
            Bitmap bitmap=BitmapFactory.decodeFile(inmagePath);
            Bitmap b=Circle1.createCircle(bitmap);
            mHeadImage.setImageBitmap(b);
        }else{
            Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获得相册中图片的路径
     * @param externalContentUri
     * @param selection
     * @return
     */
    private String getImagePath(Uri externalContentUri, String selection) {
        String path=null;
        Cursor cursor=getContentResolver().query(externalContentUri,null,selection,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }





}

// file:///storage/emulated/0/Android/data/com.example.zheng.qq/cache/head.image